import { pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";


export const users = pgTable(
  "users",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    clerkId: text("clerk_id").unique().notNull(),
    name: text("name").notNull(),
    // Todo: add banner fields
    imageUrl: text("image_url").notNull(),
    createdAt: timestamp("created_at").defaultNow().notNull(),
    updatedAt: timestamp("updated_at").defaultNow().notNull(),
  },
  (t) => [uniqueIndex("clerk_id_idx").on(t.clerkId)]
);

export const userRelations = relations(users, ({ many }) => ({
  videos: many(vedios),
}));


export const categories = pgTable(
  "categories",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    name: text("name").notNull().unique(),
    description: text("description"),
    createdAt: timestamp("created_at").defaultNow().notNull(),
    updatedAt: timestamp("updated_at").defaultNow().notNull(),
  },
  (t) => [uniqueIndex("name_idx").on(t.name)]
);

export const categoryRelations = relations(users, ({ many }) => ({
  videos: many(vedios),
}));


// 视频表
export const vedios = pgTable(
  "vedios",
  {
      id: uuid("id").primaryKey().defaultRandom(),
      title: text("title").notNull(),
      description: text("description"),
      muxStatus: text("mux_status"),
      muxAssetId: text("mux_asset_id").unique(),
      muxUploadId: text("mux_upload_id").unique(),
      muxPlaybackId: text("mux_playback_id").unique(),
      muxTrackId: text("mux_track_id").unique(),
      muxTrackStatus: text("mux_track_status"),
      userId: uuid("user_id").references(()=>users.id,{onDelete:"cascade"}).notNull(),
      categoryId: uuid("category_id").references(()=>categories.id,{onDelete:"set null"}),
      createdAt: timestamp("created_at").defaultNow().notNull(),
      updatedAt: timestamp("updated_at").defaultNow().notNull(),
  }
)

// 视频关系
export const vedioRelations = relations(vedios,({one})=>({
  user:one(users,{
    fields:[vedios.userId],
    references:[users.id]
  }),
  category:one(categories,{
    fields:[vedios.categoryId],
    references:[categories.id]
  }),
}))